package com.kafka.test.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/03/21/08:45
 * @Description:
 */

/**
 * 关闭提交偏移量，默认5s保存一次
 */
public class ConsumerTestAutoOffset {
    public static void main(String[] args) {

//         创建配置对象
        Map<String, Object> configMap = new HashMap<>();
        configMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
//         反序列化类配置
        configMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        configMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
//         组ID配置
        configMap.put(ConsumerConfig.GROUP_ID_CONFIG, "test");
//        关闭自动提交偏移量
        configMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,false);

        //  创建消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(configMap);
        //  从kafka主题中获取对象 订阅主题
        consumer.subscribe(Collections.singleton("test"));
        // 消费者从Kafka主题中拉取数据
        while (true) {
            ConsumerRecords<String, String> datas = consumer.poll(100);
            for (ConsumerRecord<String, String> data : datas) {
                System.out.println(data);
            }
            // todo 手动保存偏移量
            consumer.commitAsync(); // 异步提交
//            consumer.commitSync(); // 同步提交
        }
        //  关闭消费者对象
        // consumer.close();
    }
}
